'use strict';

const Service = require('egg').Service;

class HomeService extends Service {
    async index() {
        const {
            ctx,
            app
        } = this;
        ctx.body = 'hi, egg';
    }
    async getUserList(roles) {
        try{
            const { app } = this
            const list = await app.mysql.query('select * from users where roles=?', roles)
            return list
        } catch(e) {
            return {
                code: 0,
                message: e.message
            }
        }
    }
    async login(username, password) {
        try {
            const {
                app
            } = this;
            const result = await app.mysql.query('select * from users where username=? and password=?',[username, password])
            console.log(result)
            if (result.length > 0) {
                const token = app.jwt.sign({ username }, app.config.jwt.secret, { expiresIn: '1h' });
                return {
                    code: 200,
                    message: '登录成功',
                    data: {
                        token: token
                    }
                }
            } else {
                return {
                    code: 0,
                    message: '此用户不存在',
                }
            }

        } catch (e) {
            return {
                code: 0,
                message: e.message,
            };
        }
    }
    async getInfo(username) {
        try {
            let user = await this.app.mysql.query('select * from users where username=?', username)
            if(user.length > 0) {
                return {
                    code: 200,
                    data: {
                        roles: user[0].roles.split(','),
                        name: username,
                        avatar: "",
                        introduction: 'test'
                    }
                }
            } else {
                return {
                    code: 0,
                    message: '查找失败'
                }
            }
        } catch (e) {
            return {
                code: 0,
                message: e.message
            }
        }
    }
}

module.exports = HomeService;